package org.sasha.roulette;

import java.io.Serializable;

import com.vaadin.Application;
import com.vaadin.service.ApplicationContext.TransactionListener;

@SuppressWarnings("serial")
public class SessionContext implements Serializable, TransactionListener {

    private static ThreadLocal<SessionContext> INSTANCE = new ThreadLocal<SessionContext>();

    private final Application app;
    
    private int sessionId;
    
    protected SessionContext(final Application app) {
        super();
        this.app = app;
    }
    
    public static void initialize(final Application app) {
        final SessionContext context = new SessionContext(app);
        app.getContext().addTransactionListener(context);
        INSTANCE.set(context);
    }
    
    @Override
    public void transactionStart(Application application, Object transactionData) {
        if (application.equals(app)) {
            INSTANCE.set(this);
        }
    }

    @Override
    public void transactionEnd(Application application, Object transactionData) {
        INSTANCE.remove();
    }
    
    public int getSessionId() {
        return sessionId;
    }
    
    public void setSessionId(int sessionId) {
        this.sessionId = sessionId;
    }
    
    public static SessionContext get() {
        return INSTANCE.get();
    }
}
